﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Jumpton.SFA.Server.BusinessRule.MasterData;
using Jumpton.SFA.Server.Entity;
using Jumpton.SFA.Server.BusinessRule;
using Jumpton.SFA.Server.BusinessRule.System;
using Jumpton.SFA.Server.BusinessRule.InStoreDataMeasures;
using Jumpton.Persistent;
using BusinessRule.System;

public partial class CallRoute_Visit_History_List : PageBase
{
    private OrgainzationManager orgManager = new OrgainzationManager();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (txtHidOrg.Value == "")
        {
            txtHidOrg.Value = OrgHidValue;
            txtOrg.Text = OrgShowValue;
            var data = new OrgainzationManager().SearchOrgTree(MyStateManager.DomainID, MyStateManager.OrgID, null);
            //OrgHelper.BindUsersDDL(MyStateManager.DomainID, this.txtHidOrg.Value, this.ddlMobileUser);
            if (data.Rows.Count != 1 || new Jumpton.SFA.Server.BusinessRule.System.UserManager().isManager(MyStateManager.PersonID))
            {
                OrgHelper.BindUsersDDL(MyStateManager.DomainID, this.txtHidOrg.Value, this.ddlMobileUser);
            }
            else
            {
                Person person = new PersonManager().Load(MyStateManager.PersonID);
                ddlMobileUser.Items.Clear();
                ddlMobileUser.Items.Add(new ListItem(person.Name, MyStateManager.UserID.ToString()));
                ddlMobileUser.Items.Insert(0, new ListItem("--所有--", "0"));
            }


        }
        if (!IsPostBack)
        {
            ddl_Thrid.Visible = false;
            img_Serach.Attributes.Add("onclick",
                 "openPopup('../System/PopupOrganization.aspx?NameControlId="+txtOrg.UniqueID+"&UserListControlID="+txtHidUsers.UniqueID+"&ValueControlId="+txtHidOrg.UniqueID+"&SelectType=multi','','300','500');");
            DataBind();
            InitForm();
            ddlMobileUser.Items.Insert(0, new ListItem("--所有--", "0"));
        }

    }

    protected void InitForm()
    {
        if (Request.QueryString.Count < 1)
        {
            TxtStartDate.Text = DateTime.Now.AddDays(-6).ToString("yyyy-MM-dd");
            txtEndDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
            return;
        }

        if (!string.IsNullOrEmpty(Request.QueryString["customer"]))
            txtCode.Text = Request.QueryString["customer"];

        if (!string.IsNullOrEmpty(Request.QueryString["user"]))
            ddlMobileUser.SelectedValue = Request.QueryString["user"];

        if (!string.IsNullOrEmpty(Request.QueryString["startdate"]))
            TxtStartDate.Text = Request.QueryString["startdate"];

        if (!string.IsNullOrEmpty(Request.QueryString["enddate"]))
            txtEndDate.Text = Request.QueryString["enddate"];

        BindGrid();

    }

    /// <summary>
    /// 数据绑定
    /// </summary>
    private void BindGrid()
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        if (!string.IsNullOrEmpty(txtHidOrg.Value)&&ddl_IsThrid.SelectedValue=="1")
        {
            sb.Append(string.Format(" AND V.ORG_ID {0} ", ddl_IsThrid.SelectedValue=="1"? "IN ("+txtHidOrg.Value+")":"= 2"));
        }

        if (ddl_IsThrid.SelectedValue=="2")
        {
            if (int.Parse(ddl_Thrid.SelectedValue)!=0)
            {
                sb.Append(string.Format(" AND V.ORG_ID= {0} ", int.Parse(ddl_Thrid.SelectedValue)));
            }
            sb.Append(string.Format(" AND p.type = 2 "));
        }

        if (TxtStartDate.Text != string.Empty)
        {
            sb.Append(" AND V.[START_TIME] >=" + BusinessLogic.GetDateTimeString(DateTime.Parse(TxtStartDate.Text)));
        }
        if (txtEndDate.Text != string.Empty)
        {
            sb.Append(" AND V.[STOP_TIME] <=" + BusinessLogic.GetDateTimeString(DateTime.Parse(txtEndDate.Text).AddDays(1)));
        }
        if (ddlMobileUser.SelectedValue != string.Empty && ddlMobileUser.SelectedValue != "0")
        {
            sb.Append(" AND V.[PERSON_ID] IN (SELECT PERSON_ID FROM USERS U WHERE U.ID ='" + ddlMobileUser.SelectedValue + "') ");
        }
        if (txtCode.Text != string.Empty)
        {
            sb.Append(" AND (C.[CODE] LIKE '%" + txtCode.Text.Trim() + "%' or C.[NAME] LIKE '%" + txtCode.Text.Trim() + "%' or CI.[ADDRESS_LINE] like  '%" + txtCode.Text.Trim() + "%' "
                + " or C.default_ship_to_code LIKE '%" + txtCode.Text.Trim() + "%' or  "
                + " CI.telephone LIKE '%" + txtCode.Text.Trim() + "%' or  CI.fax LIKE '%" + txtCode.Text.Trim() + "%' "
                + " )   ");
        }
        sb.Append(" AND C.DOMAIN_ID = "+ MyStateManager.DomainID);
        sb.Append(" ORDER BY V.[STOP_TIME] DESC");
        DataSet ds = OrderHeaderManager.SearchHistoryCustomer(sb.ToString());
        if (ds != null && ds.Tables.Count > 0)
        {
            GridPager1.DataSource = ds.Tables[0];
            GridPager1.GridView = gvChannelType;
            GridPager1.BindData();
            GridPager1.Visible = gvChannelType.Rows.Count > 0;


        }
    }

    /// <summary>
    /// 数据查询
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnQueryCustomer_Click(object sender, EventArgs e)
    {
        BindGrid();
    }

    /// <summary>
    /// 绑定下拉框数据
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gvChannelType_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            HyperLink link_code = (HyperLink)e.Row.FindControl("link_code");
            HyperLink link = (HyperLink)e.Row.FindControl("link");
            string VisitID = gvChannelType.DataKeys[e.Row.RowIndex].Values["VISITID"].ToString();
            string customer = txtCode.Text.Trim();
            string user = ddlMobileUser.SelectedValue;
            string startTime = TxtStartDate.Text.ToString();
            string endTime = txtEndDate.Text.ToString();
            //string visitType = ddlVisitType.SelectedValue;
            //string visitMode = ddlVisitMode.SelectedValue;
            //string msg = string.Format("&customer={0}&user={1}&startdate={2}&enddate={3}&visittype={4}&visitmode={5}", customer, user, startTime, endTime, visitType, visitMode);
            string visitType ="0";
            string visitMode = "0";
            string msg = string.Format("&customer={0}&user={1}&startdate={2}&enddate={3}&visittype={4}&visitmode={5}", customer, user, startTime, endTime, visitType, visitMode);


            link.NavigateUrl = "Visit_History_Detail.aspx?visit=" + VisitID + msg;
            link_code.NavigateUrl = link.NavigateUrl;
            try
            {
                e.Row.Cells[3].Text = BusinessLogic.GetDateTime(e.Row.Cells[3].Text, "yyyyMMddHHmmss", "yyyy-MM-dd HH:mm:ss");
            }
            catch { }
        }
    }

    protected void btnQuery0_Click(object sender, EventArgs e)
    {
        string query = string.Empty;
        query = query + "?Table=Visits&BeginTime=" + DateTime.Parse(TxtStartDate.Text).ToString("yyyyMMddHHmmss");
        query += "&EndTime=" + DateTime.Parse(txtEndDate.Text).AddDays(1).ToString("yyyyMMddHHmmss"); ;
        query += "&org=" + txtHidOrg.Value;
        query += "&name=" + txtCode.Text;
        //query += "&visitType=" + ddlVisitType.SelectedValue;
        //query += "&visitMode=" + ddlVisitMode.SelectedValue;
        query += "&visitType=0";
        query += "&visitMode=0";
        query += "&user=" + ddlMobileUser.SelectedValue;
        query += "&flag=visitDetail";

        Response.Redirect("..\\ExportExcel\\ExportExcel.aspx" + query);
    }

    protected void gvChannelType_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvChannelType.PageIndex = e.NewPageIndex;
        BindGrid();
    }
    protected void txtOrg_TextChanged(object sender, EventArgs e)
    {
        ddlMobileUser.Items.Clear();

        if (!string.IsNullOrEmpty(txtHidUsers.Value))
        {
            string[] options = txtHidUsers.Value.Split('∮');

            for (int i = 0; i < options.Length; i++)
            {
                string[] item = options[i].Split('∞');
                ddlMobileUser.Items.Add(new ListItem(item[1], item[0]));
            }
        }
        ddlMobileUser.Items.Insert(0, new ListItem("--所有--", ""));
    }
    protected void ddl_IsThrid_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddl_IsThrid.SelectedValue=="1")
        {
            ddl_Thrid.Visible = false;
            txtOrg.Visible = true;
            img_Serach.Visible = true;
            txtOrg_TextChanged(sender, e);
        }
        else if (ddl_IsThrid.SelectedValue == "2")
        {
            ddl_Thrid.Visible = true;
            txtOrg.Visible = false;
            img_Serach.Visible = false;
            BandDataForThrid();
            ddl_Thrid_SelectedIndexChanged(sender, e);
        }
    }

    private void BandDataForThrid()
    {
        ddl_Thrid.DataSource = new  ThirdPartyCompaniesManager().GetThirdPartyCompanies(MyStateManager.DomainID, "");
        ddl_Thrid.DataValueField = "ID";
        ddl_Thrid.DataTextField = "NAME";
        ddl_Thrid.DataBind();
        ddl_Thrid.Items.Insert(0, new ListItem("--所有--", "0"));
    }
    protected void ddl_Thrid_SelectedIndexChanged(object sender, EventArgs e)
    {
        string sql = String.Format(@" select u.ID,p.NAME from USERS u inner join PERSONS p 
                     on u.PERSON_ID=p.ID and p.TYPE=2
                     and u.ACTIVE=1 and p.ACTIVE =1 and u.DOMAIN_ID={0} ",MyStateManager.DomainID); 
        if (ddl_Thrid.SelectedValue!=""&&ddl_Thrid.SelectedValue!="0")
        {
            sql = sql + " and P.org_id  = "+ Convert.ToInt32(ddl_Thrid.SelectedValue);
        }
        else
        {
            sql = sql + " and P.org_id in (select ID from THIRDPARTY_COMPANIES ) ";
        }
        sql += " order by P.NAME ";
        ThirdPartyPersonManager tppManager = new ThirdPartyPersonManager();
        ddlMobileUser.DataSource = tppManager.GetThirdPartyCompaniesPersons(sql);
        ddlMobileUser.DataValueField = "ID";
        ddlMobileUser.DataTextField = "NAME";
        ddlMobileUser.DataBind();
        ddlMobileUser.Items.Insert(0, new ListItem("--所有--", "0"));
    }
}
